package com.ddm.utils;
import cn.hutool.json.JSONUtil;
import cn.hutool.core.lang.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ExamHistoryCache {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    // 存储用户的历史记录（Key格式：exam:history:{userId}:{examId}）
    public void pushQuestionHistory(Long userId, Long examId, Long questionId) {
        try {
            String key = buildKey(userId, examId);
            String json = redisTemplate.opsForValue().get(key);
            List<Long> history = Optional.ofNullable(json)
                    .map(str ->  JSONUtil.toBean(str, new TypeReference<List<Long>>() {}, false))
                    .orElse(new ArrayList<>());
            history.add(questionId); // 添加新题目到列表末尾
            redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(history));
            redisTemplate.expire(key, 4, TimeUnit.HOURS);
        } catch (RedisConnectionFailureException e) {
            log.warn("Redis连接失败，跳过历史记录缓存: " + e.getMessage());
        } catch (Exception e) {
            log.error("缓存历史记录失败: " + e.getMessage());
        }
    }

    // 获取历史记录列表
    public List<Long> getHistory(Long userId, Long examId) {
        try {
            String key = buildKey(userId, examId);
            String json = redisTemplate.opsForValue().get(key);
            return Optional.ofNullable(json)
                    .map(str -> JSONUtil.toBean(str, new TypeReference<List<Long>>() {}, false))
                    .orElse(new ArrayList<>());
        } catch (RedisConnectionFailureException e) {
            log.warn("Redis连接失败，返回空历史记录: " + e.getMessage());
            return new ArrayList<>();
        } catch (Exception e) {
            log.error("获取历史记录失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }

    // 获取上一题ID（历史记录中倒数第二个元素）
    public Long getPreviousQuestionId(Long userId, Long examId) {
        List<Long> history = getHistory(userId, examId);
        if (history.size() < 2) {
            return null; // 历史记录不足，无上一题
        }
        return history.get(history.size() - 2); // 倒数第二个是上一题
    }

    // 移除当前题目（删除最后一个元素）
    public void popLatestQuestion(Long userId, Long examId) {
        try {
            String key = buildKey(userId, examId);
            List<Long> history = getHistory(userId, examId);
            if (!history.isEmpty()) {
                history.remove(history.size() - 1); // 删除最后一个元素
                redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(history));
            }
        } catch (RedisConnectionFailureException e) {
            log.warn("Redis连接失败，跳过历史记录更新: " + e.getMessage());
        } catch (Exception e) {
            log.error("更新历史记录失败: " + e.getMessage());
        }
    }

    public String buildKey(Long userId, Long examId) {
        return String.format("exam:history:%d:%d", userId, examId);
    }
}